//index.js
//获取应用实例
const app = getApp()

Page({
  data: {

  },
  onShow: function () {
    var that = this
    if (wx.getStorageSync('logged') == true) {
      that.setData({
        logged: true
      })
      setTimeout(function () {
        wx.switchTab({
          url: '../home/home',
        })
      }, 1000)

    }
  },

  doLogin: function (e) {
    //获取用户信息 并存放到全局变量中
    wx.login({
      success: function (r) {
        //获取临时凭证
        var code = r.code;
        wx.getUserInfo({
          success: function (res) {
            app.globalData.userInfo = e.detail.userInfo
            console.log({
              encryptedData: res.encryptedData,
              iv: res.iv,
              code: code
            })
            //调用后端
            wx.request({
              url: 'http://localhost:8080/WXLogin',
              data: {
                encryptedData: res.encryptedData,
                iv: res.iv,
                code: code
              },
              method: "GET",
              success: function (result) {
                if (result.data.status == 1) {
                  console.log(result.data);
                  app.globalData.userInfo = result.data;
                  wx.setStorageSync('logged', true);
                  wx.setStorageSync('openid', result.data.userId);

                } else {
                  console.log('解密失败')
                }
              },
              fail: function () {
                console.log("系统错误")
              }
            })
          }
        })
      },
      fail: function () {
        console.log("获取用户信息失败")
      }
    }),
      //用来转跳到第一个界面
      wx.switchTab({
        url: '../home/home',
      })
  }

})